package com.whmall.service.crm.util;

import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.*;

/**
 * 线程池
 */
public class ThreadPool {

    private static final int CORES = Runtime.getRuntime().availableProcessors();

    /** IO密集型线程池 */
    private static ExecutorService executorService = new ThreadPoolExecutor(2*CORES + 1, 4*CORES,
            60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10000));

    /**
     * 执行一个线程
     * @param runnable
     * @throws Exception
     */
    public static void execute(Runnable runnable) throws Exception {
        executorService.execute(runnable);
    }

    /**
     * 提交一个线程，返回Future
     * @param runnable
     * @return
     * @throws Exception
     */
    public static Future<?> submit(Runnable runnable) throws Exception {
        return executorService.submit(runnable);
    }

    /**
     * 等待所有线程执行结束
     * @param futures
     * @param timeout
     */
    public static void waitAllDone(List<Future<?>> futures, long timeout){
        if(CollectionUtils.isEmpty(futures)){
            return;
        }
        Assert.isTrue(timeout > 0, "参数错误");
        final long startTime = System.currentTimeMillis();
        boolean allDone;
        while(System.currentTimeMillis() - startTime < timeout) {
            allDone = true;
            for (Future<?> future : futures) {
                if(!future.isDone()) {
                    allDone = false;
                    break;
                }
            }
            if(allDone){
                break;
            }
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
